import 'remote-web-worker';
const worker = new Worker('https://cdn.jsdelivr.net/npm/console-log-hello-world', {
  type: 'classic',
});
worker.addEventListener('message', (msg) => {
  console.log('msg from remote', msg);
});
document.body.innerHTML = `
	<pre id="history"></pre>
	<form>
	<input id="message" type="text">
	<button id="send">Send Message</button>
	</form>
	<p>Computing fibonacci without worker:</p>
	<input id="fib1" type="number">
	<pre id="output1"></pre>
	<p>Computing fibonacci with worker:</p>
	<input id="fib2" type="number">
	<pre id="output2"></pre>
`;

const history = document.getElementById('history');
const message = document.getElementById('message');
const send = document.getElementById('send');
const fib1 = document.getElementById('fib1');
const output1 = document.getElementById('output1');
const fib2 = document.getElementById('fib2');
const output2 = document.getElementById('output2');

/// CHAT with shared worker ///

const chatWorker = new SharedWorker(new URL('./chat-worker.js', import.meta.url), {
  name: 'chat',
  type: 'module',
});

let historyTimeout;
const scheduleUpdateHistory = () => {
  clearTimeout(historyTimeout);
  historyTimeout = setTimeout(() => {
    chatWorker.port.postMessage({ type: 'history' });
  }, 1000);
};
scheduleUpdateHistory();

const from = `User ${Math.floor(Math.random() * 10000)}`;

send.addEventListener('click', (e) => {
  chatWorker.port.postMessage({
    type: 'message',
    content: message.value,
    from,
  });
  message.value = '';
  message.focus();
  e.preventDefault();
});

chatWorker.port.onmessage = (event) => {
  const msg = event.data;
  switch (msg.type) {
    case 'history':
      history.innerText = msg.history.join('\n');
      scheduleUpdateHistory();
      break;
  }
};

/// FIBONACCI without worker ///

fib1.addEventListener('change', async () => {
  try {
    const value = parseInt(fib1.value, 10);
    const { fibonacci } = await import('./fibonacci');
    const result = fibonacci(value);
    output1.innerText = `fib(${value}) = ${result}`;
  } catch (e) {
    output1.innerText = e.message;
  }
});

/// FIBONACCI with worker ///

const fibWorker = new Worker(new URL('./fib-worker.js', import.meta.url), {
  name: 'fibonacci',
  type: 'module',
});

fib2.addEventListener('change', () => {
  try {
    const value = parseInt(fib2.value, 10);
    fibWorker.postMessage(`${value}`);
  } catch (e) {
    output2.innerText = e.message;
  }
});

fibWorker.onmessage = (event) => {
  output2.innerText = event.data;
};
